import requests
import json
import pandas as pd
from typing import Dict, Any, Tuple, Optional

def get_api_data(client_id: str, client_secret: str, eiInfo: Dict[str, Any], 
                 service_url: str, token_url: Optional[str] = None) -> Tuple[pd.DataFrame, Dict]:
    """
    获取API数据并转换为DataFrame
    
    Args:
        client_id: 客户端ID
        client_secret: 客户端密钥
        eiInfo: API请求参数
        service_url: API服务地址
        token_url: Token获取地址（可选，默认为宝钢平台地址）
        
    Returns:
        tuple: (包含数据的DataFrame, 原始JSON响应)
    """
    # 设置默认Token获取地址
    if token_url is None:
        token_url = 'http://eplat.baogang.info/base-security-service/oauth/token'
    
    try:
        # 1. 获取Token
        token_params = {
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'client_credentials',
            'scope': 'read'
        }
        
        token_response = requests.post(token_url, params=token_params)
        token_response.raise_for_status()  # 检查HTTP错误
        
        token_data = token_response.json()
        token = token_data.get('access_token')
        
        if not token:
            raise ValueError("未能获取有效的access_token")
        
        print("Token获取成功")
        
        # 2. 调用API
        headers = {
            'Xplat-Token': token,
            'Content-type': 'application/json'
        }
        
        api_response = requests.post(
            service_url,
            headers=headers,
            data=json.dumps(eiInfo)
        )
        api_response.raise_for_status()  # 检查HTTP错误
        
        print("API调用成功")
        
        # 3. 处理响应数据
        json_data = api_response.json()
        
        # 检查响应结构
        if '__blocks__' in json_data and 'result' in json_data['__blocks__']:
            result_block = json_data['__blocks__']['result']
            
            # 提取元数据和行数据
            meta = result_block.get('meta', {})
            rows = result_block.get('rows', [])
            
            # 提取列名
            if 'columns' in meta:
                column_names = [col['name'] for col in meta['columns']]
            else:
                # 如果没有列元数据，尝试从第一行推断
                if rows:
                    column_names = list(rows[0].keys())
                else:
                    column_names = []
            
            # 创建DataFrame
            df = pd.DataFrame(rows)
            if column_names and not df.empty:
                df.columns = column_names
            
            return df, json_data
        else:
            # 如果响应结构不符合预期，直接返回原始数据
            print("警告: 响应结构不符合预期，返回原始JSON")
            return pd.DataFrame(), json_data
            
    except requests.exceptions.RequestException as req_ex:
        print(f"请求错误: {req_ex}")
        return pd.DataFrame(), {}
    except json.JSONDecodeError as json_ex:
        print(f"JSON解析错误: {json_ex}")
        return pd.DataFrame(), {}
    except Exception as ex:
        print(f"未知错误: {ex}")
        return pd.DataFrame(), {}

# 使用示例
if __name__ == "__main__":
    # 示例1: 使用宝钢平台
    client_id = 'bszhys-web1h6bwlJ4q330e73w8'
    client_secret = '6E9F8290FF2355E82F699C9AF9BC93BC'
    
    eiInfo = {
        "params": {"realEndWorkTimeBegin": "20241101220000", "realEndWorkTimeEnd": "20241102220000"},
        "showCount": "true",
        "offset": "0",
        "limit": 3,
    }
    service_url = 'http://eplat.baogang.info/service/D_A_BGTAZZWL_V_TDOPJ11_705442_02'
    
    df, raw_data = get_api_data(client_id, client_secret, eiInfo, service_url)
    
    print("\nDataFrame结果:")
    print(df)
    
    print("\n原始JSON数据:")
    print(json.dumps(raw_data, indent=2, ensure_ascii=False))
    
    # 示例2: 使用其他平台
    other_eiInfo = {
        "subjectEname": "Q01_DecisionData",
        "materialNo": [313971301701]
    }
    other_service_url = 'http://eplat.baogang.info/service/D_A_BF4'
    
    other_df, other_raw_data = get_api_data(client_id, client_secret, other_eiInfo, other_service_url)
    
    print("\n其他API的DataFrame结果:")
    print(other_df)